<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<% String path = request.getContextPath(); request.setCharacterEncoding("UTF-8");
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <base href="<%=basePath%>">
    <title>车加意方案顺序配置</title>
    <jsp:include page="/WEB-INF/jsp/common/common.jsp"></jsp:include>
    <link href="css/calendar.css"  rel="stylesheet" type="text/css" >
    <link rel="stylesheet" href="<%=path%>/css/zTreeStyle/zTreeStyle.css">
    <script type="text/javascript" src="<%=path%>/js/jquery.ztree.core-3.5.js"></script>
    <script type="text/javascript" src="<%=path%>/js/jquery.ztree.excheck-3.5.js"></script>
    <script src="<%=path%>/js/jquery.divbox.js" type="text/javascript"></script>
    <style type="text/css">
        .sub-title {
            background: none repeat scroll 0 0 #ffffff;
            font-size: 100%;
            font-weight: bold;
            height: 30px;
            line-height: 30px;
            text-indent: 10px;
            width: 100%;
        }

        #detail
        {
            position:relative;
            width: 200px;
            font-size: 12px;
            background: #fff;
            border: 1px solid #000;
            z-index: 2;
            display: none;
        }

        #detail2
        {
            position:relative;
            width: 200px;
            font-size: 12px;
            background: #fff;
            border: 1px solid #000;
            z-index: 2;
            display: none;
        }
    </style>
    <script language="javascript" type="text/javascript">
        function Map(){
            this.elements = new Array();
            //获取MAP元素个数
            this.size = function() {
                return this.elements.length;
            };
            //判断MAP是否为空
            this.isEmpty = function() {
                return (this.elements.length < 1);
            };
            //删除MAP所有元素
            this.clear = function() {
                this.elements = new Array();
            };
            //向MAP中增加元素（key, value)
            this.put = function(_key, _value) {
                if(this.containsKey(_key)){
                    this.remove(_key);
                    this.elements.push( {
                        key : _key,
                        value : _value
                    });
                }else{
                    this.elements.push( {
                        key : _key,
                        value : _value
                    });
                }
            };
            //删除指定KEY的元素，成功返回True，失败返回False
            this.remove = function(_key) {
                var bln = false;
                try {
                    for (var i = 0; i < this.elements.length; i++) {
                        if (this.elements[i].key == _key) {
                            this.elements.splice(i, 1);
                            return true;
                        }
                    }
                } catch (e) {
                    bln = false;
                }
                return bln;
            };
            //获取指定KEY的元素值VALUE，失败返回NULL
            this.get = function(_key) {
                try {
                    for (var i = 0; i < this.elements.length; i++) {
                        if (this.elements[i].key == _key) {
                            return this.elements[i].value;
                        }
                    }
                } catch (e) {
                    return false;
                }
                return false;
            };
            //判断MAP中是否含有指定KEY的元素
            this.containsKey = function(_key) {
                var bln = false;
                try {
                    for (var i = 0; i < this.elements.length; i++) {
                        if (this.elements[i].key == _key) {
                            bln = true;
                        }
                    }
                } catch (e) {
                    bln = false;
                }
                return bln;
            };
            //获取map的所有values
            this.values = function() {
                var arr = new Array();
                for (var i = 0; i < this.elements.length; i++) {
                    arr.push(this.elements[i].value);
                }
                return arr;
            };
            //获取map的所有keys
            this.keys= function() {
                var arr = new Array();
                for (var i = 0; i < this.elements.length; i++) {
                    arr.push(this.elements[i].key);
                }
                return arr;
            };
            //获取数组
            this.getArray= function(){
                var arr = new Array();
                for (var i = 0; i < this.elements.length; i++) {
                    arr.push({
                        key : this.elements[i].key,
                        value : this.elements[i].value
                    });
                }
                return arr;
            };
        }
        var defaultBranch;//保存默认机构的值
        var planMap = new Map();
        // 用于存储查询条件
        var lifeConditionMap = {};
        $(document).ready(function() {
            isReadyIframe();

            loadPrivilegeBranchSelect();//加载机构下拉框

        });

        function isReadyIframe(){
            var iframe = $(window.parent.document).find("#iframe").length;
            if(iframe==0){
                window.location.href="<%=basePath%>index.jsp";
            }
        }

        //加载机构下拉框
        function loadPrivilegeBranchSelect(){
            $.ajax({
                url : "<%=path%>/CarAccidentController/queryPrivilegeBranch?"+new Date().getTime(),
                type : 'POST',
                async : false,
                dataType:'json',
                success : function(result) {
                    if(result){
                        if($.validate(result))return;

                        //接口下拉框对象
                        var privilegeBranchSelect = document.getElementById("privilegeBranch");
                        privilegeBranchSelect.length=0;

                        var data = result.data;
                        if(data.length > 0){
                            defaultBranch = data[0].deptCode;

                            for (var i = 0; i < data.length; i++) {
                                var option = new Option();
                                option.text = data[i].deptCname;
                                option.title = data[i].deptCname;
                                option.value = data[i].deptCode;

                                privilegeBranchSelect.add(option);
                            }
                        }
                    }
                }
            });
        }

        //所选机构改变时，清空相关联数据
        function clearBranchRelaField(){
            $("#partnerNo").val("");
        }

        //------------------------------------------ 合作伙伴 开始----------------------------------------------
        //打开合作伙伴 窗口
        function openChannelInfoDiv(pageIndex,obj){
            if(($.trim($('#privilegeBranch').val())).length==0){
                $.message('error',"请先选择机构");
                return;
            }
            $('#channelCode').val('');
            $('#channelName').val('');
            $("#"+obj.id).blur();
            queryTradPartners(pageIndex);
        }

        //查询 合作伙伴
        function queryTradPartners(pageIndex){
            var size = 8;
            var parentDeptCode = $.trim($('#privilegeBranch').val());
            var channelCode = $.trim($('#channelCode').val());
            var channelName = $.trim($('#channelName').val());

            $.openLoading();
            $.ajax({
                url : "<%=path%>/CarAccidentController/queryChannelInfoOfLife",
                type : 'POST',
                async : true,
                data:{
                    pageIndex:pageIndex,
                    size:size,
                    parentDeptCode:parentDeptCode,
                    channelCode:channelCode,
                    channelName:channelName
                },
                dataType:'json',
                success:function(page){
                    $.closeLoading();
                    if($.validate(page))return;

                    var radioObj ="<input class='input_fxk' name='partnerradio' type='radio' value=''>";
                    var fieldNames = "channelCode,channelName";
                    var tableContent = creatTable1(fieldNames,page,radioObj);
                    var tableObj = $("#channelInfoTable");
                    tableObj.find("tbody").remove();
                    tableObj.append(tableContent);

                    var strPage = creatChannelPage2(pageIndex,6,page.maxPage,"16");
                    var pageDIV = $("#channelInfoPageDIV");
                    pageDIV[0].innerHTML="";
                    pageDIV.append(strPage);

                    $('#channelInfoDiv').OpenDiv();

                    bindradio();
                }
            });
        }

        //点击“确定”按钮，选择合作伙伴
        function choosePartner(){
            var selectedPartner = $("input[name='partnerradio']:checked");
            if(selectedPartner.length==0){
                $.message("error", "请选择一个合作伙伴");
                return;
            }
            var selectedPartnerNo = selectedPartner.parent().parent().children(" td:eq(1)").html();
            $('#partnerNo').val(selectedPartnerNo);

            closeCurrentDIV('channelInfoDiv');
        }
        //点击“确定” ，选择 出单机构
        function chooseDept(){
            var selectedDept= $("input[name='deptradio']:checked");
            if(selectedDept.length==0){
                $.message("error", "请选择一个出单机构");
                return;
            }
            var deptCode = selectedDept.parent().parent().children(" td:eq(1)").html();
            $('#dptCde').val(deptCode);

            closeCurrentDIV('deptDiv');
        }
        //------------------------------------------ 合作伙伴 结束----------------------------------------------

        //设置行样式
        function bindredio(){
            $("input[name='radioOrderNo']").click(function(){
                $("input[name='radioOrderNo']").parent().parent().removeClass("table_highlighter");
                $(this).parent().parent().addClass("table_highlighter");
            });
        }



        //-------------------------设置“合作伙伴”、“错误信息” 展示样式  Begin-------------------------//
        //鼠标悬浮、双击内容上显示完整信息
        function showDatail(obj,location){
            var widthNum = parseInt(location);
            var result=obj.innerHTML;
            if(result!=""){
                var length =obj.scrollWidth;
                if(length>200){
                    var e = arguments.callee.caller.arguments[0]||window.event;
                    var y = e.clientY;
                    var x= document.body.offsetWidth;
                    if(x>460){
                        x=x-widthNum;
                    }
                    var div3 = document.getElementById("detail");
                    document.getElementById("detail").style.display = 'block';
                    div3.style.left=x;
                    div3.style.top=e.clientY;
                    div3.style.position="absolute";
                    $("#input")[0].innerHTML=result;
                }
            }
        }

        //关闭详细信息层
        function closeDatail(){
            document.getElementById("detail").style.display = 'none';
        }

        //双击内容 弹出完整信息层
        function copyDetail(obj,location){
            var result=obj.innerHTML;
            if(result!=""){
                var length =obj.scrollWidth;
                if(length>0){
                    var e = arguments.callee.caller.arguments[0]||window.event;
                    var y = e.clientY;
                    var x= document.body.offsetWidth;
                    if(x>460){
                        x=x-parseInt(location);
                    }
                    var div3 = document.getElementById("detail2");
                    document.getElementById("detail2").style.display = 'block';
                    div3.style.left=x;
                    div3.style.top=e.clientY;
                    div3.style.position="absolute";
                    $("#output")[0].innerHTML=result;
                }
            }
        }

        //关闭“合作伙伴”详细信息弹出层
        function closeDiv(){
            document.getElementById("detail2").style.display = 'none';
        }
        //-------------------------设置“合作伙伴”、“错误信息” 展示样式  End-------------------------//

        //弹出层表格绑定单选按钮事件，选中某个单选按钮，该按钮所在行高亮显示
        function bindradio(){
            $("input[name='partnerradio']").click(function(){
                $("input[name='partnerradio']").parent().parent().removeClass("table_highlighter");
                $(this).parent().parent().addClass("table_highlighter");
            });
        }

        //统一 关闭窗口(传入要关闭DIV的id)
        function closeCurrentDIV(obj){
            $("#"+obj).CloseDiv();
        }


        //------------------------------------------ 合作伙伴子机构 开始----------------------------------------------
        //加载subChannelTree
        function openSubChannelTreeDiv(){
            var partnerNo = $.trim($('#partnerNo').val());
            if(partnerNo.length==0){
                $.message("error", "请先选择合作伙伴");
                return;
            }

            $.openLoading();
            $.ajax({
                url : "<%=path%>/gatewayOrder/querySubChannelTree?"+new Date().getTime(),
                type : 'POST',
                async : true,
                data:{
                    parentChannelCode:partnerNo
                },
                dataType:'json',
                success:function(data){
                    $.closeLoading();
                    if($.validate(data))return;

                    if(data.length == 0){
                        $.message("error", "所选合作伙伴下没有合作伙伴子机构");return;
                    }
                    var setting = {
                        check: {
                            enable: true,
                            chkStyle: "radio",
                            radioType: "all"
                        },
                        data: {
                            simpleData: {
                                enable: true
                            }
                        }
                    };

                    $.fn.zTree.init($("#subChannelTree"), setting, data);

                    $("#subChannelTreeDiv").OpenDiv();
                }
            });
        }

        //点击“确定”按钮，选择合作伙伴子机构
        function chooseSubPartner(){
            var subChannelTree = $.fn.zTree.getZTreeObj("subChannelTree");
            if(subChannelTree.getCheckedNodes(true).length==0){
                $.message("error", "请选择一个合作伙伴子机构");
                return;
            }
            var subChannels = subChannelTree.getCheckedNodes(true);
            $("#subPartnerNo").val(subChannels[0].id);

            closeCurrentDIV('subChannelTreeDiv');
        }
        function summaryShow() {
            // 清空
            summaryHide()
            var jsonDate = checkConditions()

            if (!jsonDate) {
                $.closeLoading();
                return false
            }
            $.openLoading();
            $.ajax({
                url : "<%=path%>/lifePolicyList/queryLifePolicyAll",
                type : 'POST',
                async : true,
                dataType:'json',
                data: jsonDate,
                success:function(data){
                    $.closeLoading();
                    $.each(data, function (i, v) {
                        if(v.STATE_ID === '2') {
                            $("#countValidPolicy").text(v.COUNT_TOTAL);//有效保单笔数
                            $("#totalPremium").text(v.PREMIUM_VALID);//设置保费合计
                        } else if (v.STATE_ID === '3') {
                            $("#countOfCancel").text(v.COUNT_TOTAL);//注销保单笔数
                            $("#totalPremiumOfCancel").text(v.PREMIUM_VALID);//设置注销保费合计
                        }
                    })
                    $('#summary_div').show()
                }
            });
        }


        function queryConfigPlan(pageIndex,flag){
            var serialNumberList = $("input[name='serialNumber']");

            if(serialNumberList.length!=0){
                serialNumberList.each(function(i){
                    var obj = new Object();
                    var serialNumber = $(this).val();
                    var planNo = $(this).parent().parent().children().html();
                    obj.serialNumber = serialNumber;
                    obj.planNo = planNo;
                    planMap.put(planNo,obj);
                });
            }
            if (flag){
                planMap.clear();
            }
            if(pageIndex == null){
                pageIndex = 1;
            }
            if(pageIndex == -1){
                pageIndex = 1;
            }

            var partnerNo = $.trim($("#partnerNo").val());//合作伙伴代码
            var privilegeBranch = $.trim($("#privilegeBranch").val());//出单机构

            $.openLoading();
            $.ajax({
                url : "<%=path%>/CarAccidentController/queryConfigPlanByCriteria",
                type : 'POST',
                data:{
                    pageIndex:pageIndex,
                    privilegeBranch:privilegeBranch,
                    partnerNo:partnerNo,
                },
                async : true,
                dataType:'json',
                success:function(page){
                    $.closeLoading();
                    if($.validate(page))return;
                    if(page.result == 'noChannelInfo'){
                        //清空表格数据
                        $(".orderTable").find("tbody").remove();
                        $("#orderPageDiv").html("");
                        return;
                    }
                    // lifeConditionMap=page.map;
                    var fieldNames ='planNo,planName,isCorporation,vhlTyp,maxSeat,minSeat'
                    var lastButton = '<input type="text" value="serialNumberVal" class="input_text" id="serialNumber" onchange="changeSerialNum(this)" name="serialNumber">';
                    var tableContent = creatTable10(fieldNames,page,null,lastButton);

                    var tableObj = $("#orderTable1");
                    tableObj.show();
                    tableObj.find("tbody").remove();
                    tableObj.append(tableContent);


                    var strPage = creatChannelPage(pageIndex,6,page.maxPage,"109");
                    var pageDIV = $("#orderPageDiv");
                    pageDIV[0].innerHTML="";
                    pageDIV.append(strPage);


                    // $('#policyListDiv').OpenDiv();
                    bindredio();

                    var serialNumberList = $("input[name='serialNumber']");
                    if(planMap.elements.length > 0){
                        serialNumberList.each(function(i){
                            var planNo = $(this).parent().parent().children().html();
                            var configPlanObj = planMap.get(planNo);
                            var a = configPlanObj.planNo
                            if (planNo === configPlanObj.planNo){
                                $(this).val(configPlanObj.serialNumber);
                            }
                        });
                        console.log(planMap)
                    }
                }
            });
        }

        function changeSerialNum(t) {
            var reg = new RegExp("(^$)|(^[0-9]+$)");
            if(!(reg.test(t.value))){
                t.value="";
                $.message("error", "输入的格式不正确，正确格式只能录入数字");
                return;
            }
        }
        function updateConfigPlan() {
            $.openLoading();
            var serialNumberList = $("input[name='serialNumber']");
            var TradConfigList = new Array();


            serialNumberList.each(function () {
                var serialNumber = $(this).val();
                var planNo = $(this).parent().parent().children().html();
                var TradConfig = new Object();
                TradConfig.planNo = planNo;
                TradConfig.serialNumber = serialNumber;
                planMap.put(TradConfig.planNo,TradConfig);
            })
            for(i in planMap.keys()){
                var key = planMap.keys()[i];
                TradConfigList.push(planMap.get(key))
            }

            var TradConfigListStr = JSON.stringify(TradConfigList);
            console.log(TradConfigList);
            $.ajax({
                url: "<%=path%>/CarAccidentController/updateConfigPlanList",
                data: TradConfigListStr,
                type : 'POST',
                dataType:'json',
                headers: {
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                success:function (data) {
                    $.closeLoading();
                    if (data.result === "success"){
                        $.message("success",data.message)
                    }else {
                        $.message("error",data.message);
                    }
                }
            })
            queryConfigPlan(1,true)
        }
    </script>
</head>
<body>
<div class="current">
    <table class="current_table_1">
        <tbody>
        <tr class="f2">
            <td><img src="./images/current_1.jpg"></td>
            <td class="current_table_1_td">
                <img src="images/current_1.png">&nbsp;您现在的位置：&nbsp;
                <span style=" color:#136bab; ">统计分析
	                  	<span style="padding:0 5px; font-weight:bold; line-height:28px;">&gt;</span>意健险数据导出
	                  </span>
            </td>
            <td><img src="./images/current_3.jpg"></td>
        </tr>
        </tbody>
    </table>
</div>

<!--查询条件及结果表单 -->
<table border="1" class="table_02" style="height:150px">
    <tr height="50px">
        <td colspan="2" align="center">
            <form method="post" id="searchCariteriaForm">
                <table border="0" style="margin: 12px auto;">
                    <div style="margin-right: 10px">
                        <tr>
                            <td style="border: 0;text-align: right" nowrap="nowrap">合作伙伴：</td>
                            <td style="border: 0 ;text-align: left; padding-right: 70px"><input name="partnerNo" id="partnerNo" readonly="readonly" onselect="" style=" background-color: #ccc;" class="input_text">&nbsp;&nbsp;<input type="button"  class="input_button_5"  id="searchPartnerBtn" value="请选择" onClick="openChannelInfoDiv(1,this)"/></td>
                            <td style="padding-left:40px; border: 0;text-align: right" nowrap="nowrap">分公司：</td>
                            <td style="border: 0;text-align: left;padding-right: 70px">
                                <select class="search_select_1" name="privilegeBranch" id="privilegeBranch" onchange="clearBranchRelaField()" style="width: 206px"></select>
                            </td>
                        </tr>
                    </div>
                    <div>
                        <tr>
                            <td colspan="6" style="border: 0;padding-top: 5px;padding-right: 70px">
                                <input type="button"  class="input_button_2"  value="查询方案"    onClick="queryConfigPlan(1,true)"/>
                            </td>
                        </tr>
                    </div>
                </table>
            </form>
        </td>
    </tr>
</table>
<div style="width:100%;">
    <table class="table_02" id="orderTable1">
        <thead>
        <tr>
            <th nowrap="nowrap" style="width:5%">投保方案号</th>
            <th nowrap="nowrap" style="width:5%">投保方案名称</th>
            <th nowrap="nowrap" style="width:10%">是否总公司方案</th>
            <th nowrap="nowrap" style="width:5%">适用的车辆使用性质</th>
            <th nowrap="nowrap" style="width:5%">适用的最大座位数</th>
            <th nowrap="nowrap" style="width:5%">适用的最小座位数</th>
            <th nowrap="nowrap" style="width:5%">显示序号</th>
        </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>
<div><input type="button" value="保存修改" class="input_button_2" id="updateConfigPlan" onclick="updateConfigPlan()"></div>
<div id="orderPageDiv"  class="page">
</div>

<!--选择 合作伙伴 div 默认隐藏-->
<div id="channelInfoDiv" style="display:none;width:80%;">
    <div class="table_title_div">
        <table class="table_title" style='width:100%;height: 20px;'>
            <tr>
                <td width="10%"></td>
                <td width="80%" id="interfaceName"></td>
                <td width="10%" align="right"><img src="./images/closedown.gif" alt="关闭"  onclick="closeCurrentDIV('channelInfoDiv')"/></td>
            </tr>
        </table>
    </div>
    <table class="table_02" id="table" style="height:180px;" align="center">
        <tr>
            <td>
                <table class="search_table">
                    <tr height="30px">
                        <td colspan="3" style="text-align:center">
                            合作伙伴代码：<input name="txt3"  id="channelCode"  type="text" class="input_text" value="" >&nbsp;&nbsp;
                            合作伙伴名称：<input name="txt3" id="channelName"  type="text" class="input_text" value="">&nbsp;&nbsp;
                            <input type="button"  class="input_button_1" id="searchBtn" value="查询" onClick="queryTradPartners(1)"/>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td>
                <table id="channelInfoTable"  class="content_table_1">
                    <thead>
                    <tr class="f1">
                        <th style="width:5%">选择</th>
                        <th style="width:10%">合作伙伴代码</th>
                        <th style="width:20%">合作伙伴名称</th>
                    </tr>
                    </thead>
                    <tbody>
                    </tbody>
                </table>
                <div id="channelInfoPageDIV"  class="page"></div>
            </td>
        </tr>
    </table>
    <div align="center" >
        <input type="button" id="saveRoleBtn" value="确定" onclick="choosePartner()" class="input_button_3"/>&nbsp;&nbsp;&nbsp;
        <input type="button" value="取消" onclick="closeCurrentDIV('channelInfoDiv')" class="input_button_3"/>
    </div>
</div>


<!-- 	 鼠标悬浮”合作伙伴、错误信息“时弹出层 -->
<div id="detail" style="display:none;">
    <div id="input" style="margin:5px;word-wrap:break-word;"></div>
</div>

<!-- 	 鼠标双击”合作伙伴、错误信息“时弹出层 -->
<div id="detail2" style="display:none;">
    <h4  style='background-color:#A4BDE3;'>
        <table height="20px">
            <tr>
                <td width="200px";>
                </td>
                <td align="right">
                    <img src="./images/closedown.gif"  onclick="closeDiv()"/>
                </td>
            </tr>
        </table>
        <input type="hidden" id="appId" value="">
    </h4>
    <div id="output" style="margin:5px;word-wrap:break-word;"></div>
</div>

<%--subChannelTree(选择合作伙伴子机构层) --%>
<div id="subChannelTreeDiv" style="display: none;width:500px;margin-top: -50px" align="center">
    <div class="table_title_div">
        <table class="table_title" style='width:500px; height: 20px;'>
            <tr>
                <td width="10%"></td>
                <td width="80%" id="interfaceName"></td>
                <td width="10%" align="right"><img src="<%=path %>/images/closedown.gif" alt="关闭"  onclick="closeChannelTreeDiv()"/></td>
            </tr>
        </table>
    </div>

    <div style="height: 300px;width:500px; overflow:auto">
        <ul id="subChannelTree" class="ztree"></ul>
    </div>

    <div style="text-align: center;padding: 5px">
        <input type="button" id="choseChannelBtn" value="确定" onclick="chooseSubPartner()" class="input_button_1"/>&nbsp;&nbsp;&nbsp;
        <input type="button" value="取消" onclick="closeCurrentDIV('subChannelTreeDiv')" class="input_button_1"/>
    </div>
</div>
</body>
</html>
